﻿using Microsoft.AspNetCore.SignalR.Client;
using System.ComponentModel.DataAnnotations;
using TrackSystem.Entities.RequestFeature;
using TrackSystem.IO.Formula;
using TrackSystem.IO.Utils;

namespace TrackSystem.UI.Server.Pages.IOControl
{
    public partial class RegControlPage
    {
        private HubConnection? hubIO;

        private string Message = "无信息";

        List<KeyValuePair<string, OperandDef>>? PagedRegs;

        [Required]
        private PageParameter? pageOptions = new PageParameter()
        {
            CurrentPage = 1,
            PageSize = 20,
            Filter = ""
        };

        /// <summary>
        /// 首次渲染
        /// </summary>
        /// <param name="firstRender"></param>
        /// <returns></returns>
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                try
                {
                    // 建立SIGNALR连接
                    hubIO = new HubConnectionBuilder()
                        .WithUrl("http://localhost:5000/ioctlhub")
                        .WithAutomaticReconnect(new[] { TimeSpan.Zero, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(10) })
                        .Build();

                    await hubIO.StartAsync();

                    // 注册查询寄存器状态响应函数
                    hubIO.On<List<KeyValuePair<string, OperandDef>>, PageParameter>("HandlePagedRegs", (tt, op) =>
                    {
                        PagedRegs = tt;
                        pageOptions = op;
                        Message = $"{DateTime.Now:T} 更新数据";
                        InvokeAsync(StateHasChanged);
                    });

                    // 注册初始化寄存器响应函数
                    hubIO.On<ResultMsg>("HandleInitRegs", async (tt) =>
                    {
                        Message = tt.Msg;
                        await InvokeAsync(StateHasChanged);
                    });

                    // 注册初始化寄存器响应函数
                    hubIO.On<ResultMsg>("HandleInitRegs", (tt) =>
                    {
                        Message = tt.Msg;
                        InvokeAsync(StateHasChanged);
                    });


                    var timer = new System.Timers.Timer(1000);
                    timer.Elapsed += async (s, e) =>
                    {
                        try
                        {
                            await hubIO.SendAsync("AcquirePagedRegs", pageOptions);
                        }
                        catch (Exception ex)
                        {
                            Message = ex.Message;
                            await InvokeAsync(StateHasChanged);
                        }
                    };
                    timer.Start();

                    Message = "SignalR连接成功";
                }
                catch (Exception ex)
                {
                    Message = ex.Message;
                }
                StateHasChanged();
            }
        }

        /// <summary>
        /// 初始化寄存器
        /// </summary>
        /// <returns></returns>
        private async Task BtnInitRegs()
        {
            try
            {
                if (hubIO != null && hubIO.State == HubConnectionState.Connected)
                    await hubIO.SendAsync("InitialRegs");
            }
            catch (Exception ex)
            {
                Message = ex.Message;
                await InvokeAsync(StateHasChanged);
            }
        }

        /// <summary>
        /// 卸载寄存器
        /// </summary>
        /// <returns></returns>
        private async Task BtnUnloadRegs()
        {
            try
            {
                if (hubIO != null && hubIO.State == HubConnectionState.Connected)
                    await hubIO.SendAsync("UnloadRegs");
            }
            catch (Exception ex)
            {
                Message = ex.Message;
                await InvokeAsync(StateHasChanged);
            }
        }

        private Task OnPageClick(int pageIndex)
        {
            pageOptions.CurrentPage = pageIndex;
            return Task.CompletedTask;
        }

        private async Task OnBtnSwitch(string regName, bool sw)
        {
            if (hubIO != null && hubIO.State == HubConnectionState.Connected)
               await hubIO.SendAsync("Assign", regName, new OperandDef(sw));

        }
    }
}
